package com.qiantu.phone.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.HapticFeedbackConstants;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseActivity;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLDeviceGroupDBManager;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.DeviceBindGroupBean;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.action.StatusAction;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.TitleBarFragment;
import com.qiantu.phone.event.DeviceItemChangeEvent;
import com.qiantu.phone.event.DeviceListChangeEvent;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.event.UpdateFavouriteEvent;
import com.qiantu.phone.ui.activity.AddDevice1Activity;
import com.qiantu.phone.ui.activity.DeviceSettingActivity;
import com.qiantu.phone.ui.activity.GroupDeviceListActivity;
import com.qiantu.phone.ui.activity.KGXPanelBindDeviceActivity;
import com.qiantu.phone.ui.activity.MultipleSelectDeviceActivity;
import com.qiantu.phone.ui.activity.PanelBindDeviceActivity;
import com.qiantu.phone.ui.activity.PanelBindSelectActivity;
import com.qiantu.phone.ui.activity.SelectFloorRoomActivity;
import com.qiantu.phone.ui.activity.SmartControlActivity;
import com.qiantu.phone.ui.adapter.ManagerDeviceAdapter;
import com.qiantu.phone.ui.dialog.BottomDeviceFilterDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.widget.StatusLayout;
import com.lxj.xpopup.XPopup;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;

import static android.app.Activity.RESULT_OK;
import static com.qiantu.api.entity.RoomBean.ROOM_COMMON_SERIALNO;

/**
 * time   : 2021/12/22
 */
public final class SmartAppliancesFragment extends TitleBarFragment<AppActivity>
        implements OnRefreshLoadMoreListener, StatusAction {

    public static SmartAppliancesFragment newInstance() {
        SmartAppliancesFragment fragment = new SmartAppliancesFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    private StatusLayout mStatusLayout;
    private RecyclerView mRecyclerView;
//    private View recyclerViewShadow;
//    private TextView selectArea;
//    private CheckBox checkbox;
    private View btnFilter;
    private View btnAllSelect;
    private EditText mEditSearch;
    private ManagerDeviceAdapter mManagerDeviceAdapter;
    private View bottomDeviceOperate;
    private TranslateAnimation mShowTranslateAnimation;
    private TranslateAnimation mHideTranslateAnimation;
//    private VibratorManager mVibratorManager;

    private SearchType searchType;
    //设备大类
    private String searchKey;
    //3普通面板绑定 4kgx面板绑定
    private int selectType;
    private boolean selectable;
    private boolean isSingleSelect = false;
    private boolean showOffline = true;
    private List<DeviceBean> allDevices;
    private Map<String,Integer> selectData;
    public enum SearchType{
        SEARCH_TYPE_ALL,
        SEARCH_TYPE_DEVICETYPE,//根据设备大类检索数据
        SEARCH_TYPE_GROUP,//仅检索群组数据
        SEARCH_TYPE_GROUP_DEVICE,//检索群组对应的设备数据
        SEARCH_TYPE_GROUP_CONTAIN_DEVICE,//检索群组对应的设备数据
    }

    public static SmartAppliancesFragment newInstance(SearchType searchType,String searchKey) {
        SmartAppliancesFragment fragment = new SmartAppliancesFragment();
        Bundle args = new Bundle();
        args.putString("searchType", String.valueOf(searchType));
        args.putString("searchKey", searchKey);
        args.putInt("selectType",0);
        fragment.setArguments(args);
        return fragment;
    }

    public static SmartAppliancesFragment newInstance(SearchType searchType,String searchKey,Integer selectType) {
        SmartAppliancesFragment fragment = new SmartAppliancesFragment();
        Bundle args = new Bundle();
        args.putString("searchType", String.valueOf(searchType));
        args.putString("searchKey", searchKey);
        args.putInt("selectType",selectType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            if(!TextUtils.isEmpty(getArguments().getString("searchType"))){
                searchType = SearchType.valueOf(getArguments().getString("searchType"));
            }else{
                searchType = SearchType.SEARCH_TYPE_ALL;
            }
            searchKey = getArguments().getString("searchKey");
            selectType = getArguments().getInt("selectType");
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_smart_appliances;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mStatusLayout = findViewById(R.id.status_layout);
//        selectArea = findViewById(R.id.select_area);
//        checkbox = findViewById(R.id.checkbox);
        mRecyclerView = findViewById(R.id.recycler_view);
//        recyclerViewShadow = findViewById(R.id.recycler_view_shadow);
        bottomDeviceOperate = findViewById(R.id.bottom_device_operate);
        mEditSearch = findViewById(R.id.edit_search);
        btnFilter = findViewById(R.id.btn_filter);
        btnAllSelect = findViewById(R.id.btn_all_choose);
        setOnClickListener(R.id.btn_filter, R.id.btn_belong, R.id.btn_set_universal, R.id.btn_set_common, R.id.btn_cancel_common, R.id.btn_home_show, R.id.btn_home_hide, R.id.btn_enable, R.id.btn_disable);
        mEditSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() > 0){
                    searchDevice(s.toString());
                }else{
                    refreshData();
                }
            }
        });
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        mRecyclerView.setLayoutManager(gridLayoutManager);

        mManagerDeviceAdapter = new ManagerDeviceAdapter(getAttachActivity(),selectType);
        if(selectType == 3){
            mManagerDeviceAdapter.setIsDeviceAction(true);
        } else if(selectType == 4){
            mManagerDeviceAdapter.setIsDeviceAction(true);
        }
        mManagerDeviceAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                DeviceBean device = mManagerDeviceAdapter.getData().get(position);
                if(selectType == 3){
                    ((PanelBindDeviceActivity) getActivity()).addDevice(device);
                } else if(selectType == 4){
                    ((KGXPanelBindDeviceActivity) getActivity()).addDevice(device);
                }else{
                    if(searchType != SearchType.SEARCH_TYPE_GROUP_CONTAIN_DEVICE){

                        DeviceSettingActivity.start(getContext(), device.getDeviceSerialNo());
                    }
                }

            }
        });
        mManagerDeviceAdapter.setOnChildClickListener(R.id.checkbox, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                ArrayList<DeviceBean> selectedDevices = ((ManagerDeviceAdapter) mManagerDeviceAdapter).getSelectedData();
                if(getActivity() instanceof SmartControlActivity){
                    if (selectedDevices.size() > 0) {
                        showBottomOperateView();
                        ((SmartControlActivity) getActivity()).showCancel();
                    } else {
                        hideBottomOperateView();
                    }
                }else if(getActivity() instanceof MultipleSelectDeviceActivity){
                    ((MultipleSelectDeviceActivity) getActivity()).onSelectedDevices(selectedDevices);
                }else if(getActivity() instanceof PanelBindSelectActivity){
                    ((PanelBindSelectActivity) getActivity()).onSelectedDevices(selectedDevices);
                }else if(getActivity() instanceof GroupDeviceListActivity){
                    ((GroupDeviceListActivity) getActivity()).onSelectedDevices(selectedDevices);
                }
            }
        });
        mManagerDeviceAdapter.setOnChildClickListener(R.id.btn_sort_device_action,new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                    DeviceBean device = mManagerDeviceAdapter.getData().get(position);

                if(selectType == 3){
//                    ((PanelBindDeviceActivity) getActivity()).addDevice(device);
                    ((PanelBindDeviceActivity) getActivity()).removeData(device.getDeviceSerialNo());
                } else if(selectType == 4){
//                    ((KGXPanelBindDeviceActivity) getActivity()).addDevice(device);
                    ((KGXPanelBindDeviceActivity) getActivity()).removeData(device.getDeviceSerialNo());
                }

//                    ((PanelBindDeviceActivity) getActivity()).removeData(device.getDeviceSerialNo());
                mManagerDeviceAdapter.getItem(position).setTemporary(null);
                mManagerDeviceAdapter.notifyItemChanged(position);
            }
        });
        mManagerDeviceAdapter.setOnItemLongClickListener(new BaseAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(RecyclerView recyclerView, View itemView, int position) {
//                if (mVibratorManager == null) {
//                    mVibratorManager = new VibratorManager(getContext());
//                }
//                mVibratorManager.longClickVibrator();
                if(getActivity() instanceof SmartControlActivity){
                    itemView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
                    ((SmartControlActivity) getActivity()).goEdit();
                }
                return false;
            }
        });
        mRecyclerView.setAdapter(mManagerDeviceAdapter);
        if(selectType != 3 && selectType != 4){
            mManagerDeviceAdapter.setSelectable(selectable);
            mManagerDeviceAdapter.setSingleSelect(isSingleSelect);
            mManagerDeviceAdapter.checkSelected(mSelectedDevices);
        }
        mManagerDeviceAdapter.setShowOffline(showOffline);
        showLoading();
    }

    @Override
    protected void initData() {
        Observable.create(new ObservableOnSubscribe<List<DeviceBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<DeviceBean>> emitter) throws Exception {
                List<DeviceBean> devices;
                //设备大类不为空，根据设备大类查询设备
                if(searchType == SearchType.SEARCH_TYPE_DEVICETYPE){
                    devices = LLDeviceDBManager.getInstance(getContext()).getAvailableDeviceByMainType(searchKey);
                }else if(searchType == SearchType.SEARCH_TYPE_GROUP_DEVICE){
                    devices = LLDeviceDBManager.getInstance(getContext()).getDeviceByControllerSerialNoWithoutGroupDevice(searchKey);
                }else if(searchType == SearchType.SEARCH_TYPE_GROUP_CONTAIN_DEVICE){
                    List<String> list = new ArrayList<>();
                    list.add(searchKey);
                    List<DeviceBindGroupBean> deviceBindGroupBeanList = LLDeviceGroupDBManager.getInstance(getContext()).getDeviceGroupsByDeviceGroupSerialNo(list);
                    List<String> serialNos = new ArrayList<>();
                    for(int i = 0;i < deviceBindGroupBeanList.size();i++){
                        serialNos.add(deviceBindGroupBeanList.get(i).getDeviceSerialNo());
                    }
                    devices = LLDeviceDBManager.getInstance(getContext()).getDevicesByDeviceSerialNos(serialNos);
                }else{
                    devices = LLDeviceDBManager.getInstance(getContext()).getAll();
                }
                emitter.onNext(devices);
            }
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<DeviceBean>>() {
                    @Override
                    public void accept(List<DeviceBean> devices) throws Exception {
                        if(devices == null || devices.size() == 0){
                            showEmpty();
                        }else{
                            showComplete();
                        }
                        if(selectData != null){
                            for(DeviceBean bean : devices){
                                if(selectData.get(bean.getDeviceSerialNo()) != null){
                                    bean.setTemporary(selectData.get(bean.getDeviceSerialNo()));
                                }
                            }
                        }
                        allDevices = devices;
                        mManagerDeviceAdapter.setTotalData(devices);
//                        selectArea.setText(getString(R.string.all_device_count_holder, devices.size()));
                    }
                });
    }

    private void showEmpty(){
        showEmpty(R.attr.img_emptystate_nodevice, R.string.no_device, R.string.add, new StatusLayout.OnBtnClickListener() {
            @Override
            public void onClick(StatusLayout layout) {
                Intent intent = new Intent(getContext(), AddDevice1Activity.class);
                startActivity(intent);
            }
        });
    }

    private void refreshData() {
        //选择框还没创建就是不限区域,刷新所有的设备
        if (mBottomDeviceFilterDialog == null) {
            initData();
        } else {
            //刷新所有的设备
            Observable.create(new ObservableOnSubscribe<List<DeviceBean>>() {
                @Override
                public void subscribe(ObservableEmitter<List<DeviceBean>> emitter) throws Exception {
                    List<DeviceBean> devices = mBottomDeviceFilterDialog.getAllDeviceFormSelectArea();
                    emitter.onNext(devices);
                }
            }).subscribeOn(Schedulers.computation())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<List<DeviceBean>>() {
                        @Override
                        public void accept(List<DeviceBean> devices) throws Exception {
                            mManagerDeviceAdapter.setTotalData(devices);
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            ToastUtils.show(R.string.load_area_data_failed);
                        }
                    });
        }
    }

    private void searchDevice(String keywords){
        if(allDevices != null){
            List<DeviceBean> searchDevices = new ArrayList<>();
            for(DeviceBean deviceBean : allDevices){
                if(deviceBean.getName() != null && deviceBean.getName().contains(keywords)){
                    searchDevices.add(deviceBean);
                }
            }
            mManagerDeviceAdapter.setTotalData(searchDevices);
        }
    }

    public void setSelectable(boolean selectable) {
        this.selectable = selectable;
        if(mManagerDeviceAdapter != null){
            mManagerDeviceAdapter.setSelectable(selectable);
            if (!selectable) {
                hideBottomOperateView();
            }
        }
    }

    public void setShowOffline(boolean showOffline) {
        this.showOffline = showOffline;
    }

    public void clearSelected() {
        mManagerDeviceAdapter.setSelectedAll(false);
        hideBottomOperateView();
    }

    private List<String> mSelectedDeviceSerialNos;
    public void checkSelectedBySerialNos(List<String> deviceSerialNos){
        mSelectedDeviceSerialNos = deviceSerialNos;
        if(mManagerDeviceAdapter != null){
            mManagerDeviceAdapter.checkSelectedBySerialNo(mSelectedDeviceSerialNos);
        }
    }

    private List<DeviceBean> mSelectedDevices;
    public void checkSelected(List<DeviceBean> devices){
        mSelectedDevices = devices;
        if(mManagerDeviceAdapter != null){
            mManagerDeviceAdapter.checkSelected(devices);
        }
    }

    public List<DeviceBean> getSelectedDevices(){
        if(mManagerDeviceAdapter != null){
            return mManagerDeviceAdapter.getSelectedData();
        }
        return null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshDeviceListEvent(RefreshDeviceListEvent event) {
//        List<String> rooms = new ArrayList<>();
//        rooms.add(event.roomSerialNo);
//        refreshData(rooms);
        refreshData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeviceChangeEvent(DeviceItemChangeEvent event) {
        DeviceBean device = LLDeviceDBManager.getInstance(getContext()).getDeviceBySerialNo(event.deviceSerialNo);
        if(device != null){
            mManagerDeviceAdapter.update(device);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeviceListChangeEvent(DeviceListChangeEvent event) {
        //判断房间是否跟设备所在房间才更新
        if (event.deviceSerialNos != null && event.deviceSerialNos.size() > 0) {
            List<DeviceBean> devices = LLDeviceDBManager.getInstance(getContext()).getAvailableDevicesByDeviceSerialNos(event.deviceSerialNos);
            //查询后，没有设备关闭设备弹框
            if(devices != null && devices.size() > 0){
                mManagerDeviceAdapter.update(devices);
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_filter:
//                showSelectAreaDialog(view);
                showBottomDeviceFilterDialog();
                break;
//            case R.id.checkbox:
//                mManagerDeviceAdapter.setOnlySeeCommonly(checkbox.isChecked());
//                String text = (String) selectArea.getText();
//                selectArea.setText(text.split(" ")[0] + " (" + mManagerDeviceAdapter.getItemCount() + ")");
//                break;
            case R.id.btn_belong:
                Intent intent = new Intent(getContext(), SelectFloorRoomActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                List<DeviceBean> selectedDevices = mManagerDeviceAdapter.getSelectedData();
                if (selectedDevices != null && selectedDevices.size() == 1) {
                    intent.putExtra("roomSerialNo", selectedDevices.get(0).getRoomSerialNo());
                }
                startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
                    @Override
                    public void onActivityResult(int resultCode, Intent data) {
                        if (resultCode == RESULT_OK) {
                            String serialNo = data.getStringExtra("serialNo");
                            String roomName = data.getStringExtra("roomName");
                            String floorSerialNo = data.getStringExtra("floorSerialNo");
                            changeRoom(serialNo, roomName, floorSerialNo);
                        }
                    }
                });
                break;
            case R.id.btn_set_universal:
                new ConfirmHintDialog.Builder(getContext())
                        .setLeftBtnText(getString(R.string.cancel))
                        .setRightBtnText(getString(R.string.ok))
                        .setContent(R.string.set_common_hint)
                        .setListener(new ConfirmHintDialog.OnListener() {
                            @Override
                            public void onLeftClick(BaseDialog dialog) {
                                dialog.dismiss();
                            }

                            @Override
                            public void onConfirm(BaseDialog dialog) {
                                dialog.dismiss();
                                changeRoom(ROOM_COMMON_SERIALNO, getString(R.string.common), null);
                            }
                        })
                        .show();
                break;
            case R.id.btn_set_common:
                new ConfirmHintDialog.Builder(getContext())
                        .setLeftBtnText(getString(R.string.cancel))
                        .setRightBtnText(getString(R.string.ok))
                        .setContent(R.string.set_favourite_hint)
                        .setListener(new ConfirmHintDialog.OnListener() {
                            @Override
                            public void onLeftClick(BaseDialog dialog) {
                                dialog.dismiss();
                            }

                            @Override
                            public void onConfirm(BaseDialog dialog) {
                                dialog.dismiss();
                                setFavourite(true);
                            }
                        })
                        .show();
                break;
            case R.id.btn_cancel_common:
                new ConfirmHintDialog.Builder(getContext())
                        .setLeftBtnText(getString(R.string.cancel))
                        .setRightBtnText(getString(R.string.ok))
                        .setContent(R.string.cancel_favourite_hint)
                        .setListener(new ConfirmHintDialog.OnListener() {
                            @Override
                            public void onLeftClick(BaseDialog dialog) {
                                dialog.dismiss();
                            }

                            @Override
                            public void onConfirm(BaseDialog dialog) {
                                dialog.dismiss();
                                setFavourite(false);
                            }
                        })
                        .show();
                break;
            case R.id.btn_home_show:
                new ConfirmHintDialog.Builder(getContext())
                        .setLeftBtnText(getString(R.string.cancel))
                        .setRightBtnText(getString(R.string.ok))
                        .setContent(R.string.set_home_show_hint)
                        .setListener(new ConfirmHintDialog.OnListener() {
                            @Override
                            public void onLeftClick(BaseDialog dialog) {
                                dialog.dismiss();
                            }

                            @Override
                            public void onConfirm(BaseDialog dialog) {
                                dialog.dismiss();
                                setShowHomePage(true);
                            }
                        })
                        .show();
                break;
            case R.id.btn_home_hide:
                new ConfirmHintDialog.Builder(getContext())
                        .setLeftBtnText(getString(R.string.cancel))
                        .setRightBtnText(getString(R.string.ok))
                        .setContent(R.string.set_home_hide_hint)
                        .setListener(new ConfirmHintDialog.OnListener() {
                            @Override
                            public void onLeftClick(BaseDialog dialog) {
                                dialog.dismiss();
                            }

                            @Override
                            public void onConfirm(BaseDialog dialog) {
                                dialog.dismiss();
                                setShowHomePage(false);
                            }
                        })
                        .show();
                break;
            case R.id.btn_enable:
                new ConfirmHintDialog.Builder(getContext())
                        .setLeftBtnText(getString(R.string.cancel))
                        .setRightBtnText(getString(R.string.ok))
                        .setContent(R.string.device_enable_hint)
                        .setListener(new ConfirmHintDialog.OnListener() {
                            @Override
                            public void onLeftClick(BaseDialog dialog) {
                                dialog.dismiss();
                            }

                            @Override
                            public void onConfirm(BaseDialog dialog) {
                                dialog.dismiss();
                                deviceIsDisable(false);
                            }
                        })
                        .show();
                break;
            case R.id.btn_disable:
                new ConfirmHintDialog.Builder(getContext())
                        .setLeftBtnText(getString(R.string.cancel))
                        .setRightBtnText(getString(R.string.ok))
                        .setContent(R.string.device_disable_hint)
                        .setListener(new ConfirmHintDialog.OnListener() {
                            @Override
                            public void onLeftClick(BaseDialog dialog) {
                                dialog.dismiss();
                            }

                            @Override
                            public void onConfirm(BaseDialog dialog) {
                                dialog.dismiss();
                                deviceIsDisable(true);
                            }
                        })
                        .show();
                break;
        }
    }


    private BottomDeviceFilterDialog mBottomDeviceFilterDialog;
    private void showBottomDeviceFilterDialog() {
        if (mBottomDeviceFilterDialog == null) {
            if(searchType == SearchType.SEARCH_TYPE_GROUP_DEVICE){
                mBottomDeviceFilterDialog = new BottomDeviceFilterDialog(getContext(), BottomDeviceFilterDialog.TYPE_DEVICE, BottomDeviceFilterDialog.GROUP_DEVICE, searchKey) {
                    @Override
                    public void onConfirm(boolean hasFilter, List<DeviceBean> result) {
                        btnFilter.setSelected(hasFilter);
                        mManagerDeviceAdapter.setTotalData(result);
                    }
                };
            }else if(searchType == SearchType.SEARCH_TYPE_DEVICETYPE){
                mBottomDeviceFilterDialog = new BottomDeviceFilterDialog(getContext(), BottomDeviceFilterDialog.TYPE_DEVICE, BottomDeviceFilterDialog.AVAILABLE_DEVICE,searchKey) {
                    @Override
                    public void onConfirm(boolean hasFilter, List<DeviceBean> result) {
                        btnFilter.setSelected(hasFilter);
                        mManagerDeviceAdapter.setTotalData(result);
                    }
                };
            }else if(searchType != SearchType.SEARCH_TYPE_ALL){
                mBottomDeviceFilterDialog = new BottomDeviceFilterDialog(getContext(), BottomDeviceFilterDialog.TYPE_DEVICE, BottomDeviceFilterDialog.AVAILABLE_DEVICE,"",searchKey) {
                    @Override
                    public void onConfirm(boolean hasFilter, List<DeviceBean> result) {
                        btnFilter.setSelected(hasFilter);
                        mManagerDeviceAdapter.setTotalData(result);
                    }
                };
            }else{
                mBottomDeviceFilterDialog = new BottomDeviceFilterDialog(getContext(), BottomDeviceFilterDialog.TYPE_DEVICE) {
                    @Override
                    public void onConfirm(boolean hasFilter, List<DeviceBean> result) {
                        btnFilter.setSelected(hasFilter);
                        mManagerDeviceAdapter.setTotalData(result);
                    }
                };
            }
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .enableDrag(false)
                    .asCustom(mBottomDeviceFilterDialog);
        }
        mBottomDeviceFilterDialog.setInitCount(mManagerDeviceAdapter.getItemCount());
        List<FloorBean> floors = LLFloorDBManager.getInstance(getContext()).getNotEmptyRoomFloors();
        mBottomDeviceFilterDialog.setFloorBeans(floors);
        mBottomDeviceFilterDialog.show();
    }

    private void showBottomOperateView() {
        if (bottomDeviceOperate.getVisibility() == View.VISIBLE) {
            return;
        }
        if (mShowTranslateAnimation == null) {
            mShowTranslateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0);
            mShowTranslateAnimation.setDuration(300);//跑一个周期所用时长
            mShowTranslateAnimation.setInterpolator(new FastOutSlowInInterpolator());
        }
        bottomDeviceOperate.setVisibility(View.VISIBLE);
        bottomDeviceOperate.startAnimation(mShowTranslateAnimation);
    }

    private void hideBottomOperateView() {
        if (bottomDeviceOperate.getVisibility() == View.GONE) {
            return;
        }
        if (mHideTranslateAnimation == null) {
            mHideTranslateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1);
            mHideTranslateAnimation.setDuration(300);//跑一个周期所用时长
            mHideTranslateAnimation.setInterpolator(new FastOutSlowInInterpolator());
            mHideTranslateAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    bottomDeviceOperate.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
        bottomDeviceOperate.startAnimation(mHideTranslateAnimation);
    }

    private void changeRoom(String serialNo, String roomName, String floorSerialNo) {
        Map data = new HashMap<>();
        //1房间绑定 2房屋绑定(移除房间,绑定到房屋)
        int linkType = 0;
        if(serialNo.equals(floorSerialNo)){
            linkType = 3;
            data.put("targetSerialNo", serialNo);
        }else if (ROOM_COMMON_SERIALNO.equals(serialNo)) {
            linkType = 2;
            data.put("targetSerialNo", AppApplication.getInstance().getCurHouseInfo().getHouseSerialNo());
        } else {
            linkType = 1;
            data.put("targetSerialNo", serialNo);
        }
        data.put("type", linkType);
        List<DeviceBean> selectedDevices = mManagerDeviceAdapter.getSelectedData();
        List<String> selectedSerialNos = new ArrayList<>();
        for (DeviceBean deviceBean : selectedDevices) {
            selectedSerialNos.add(deviceBean.getDeviceSerialNo());
        }
        data.put("deviceSerialNoList", selectedSerialNos);
        int finalLinkType = linkType;
        LLHttpManager.deviceBelong(this, data,
                new HttpCallback<HttpData<Void>>(this) {
                    @Override
                    public void onStart(Call call) {
                        showDialog(null);
                    }

                    @Override
                    public void onSucceed(HttpData<Void> result) {
                        if (result.isRequestSucceed()) {
                            if (selectedDevices != null && selectedDevices.size() > 0) {
//                                List<String> deviceRooms = new ArrayList<>();
                                for (DeviceBean device : selectedDevices) {
//                                    //设置RoomSerialNo之前保存,用来更新当前选中的房间下的场景
//                                    deviceRooms.add(device.getRoomSerialNo());
                                    if(finalLinkType == 3){
                                        device.setRoomSerialNo("");
                                        device.setRoomName("");
                                    }else{
                                        device.setRoomSerialNo(serialNo);
                                        device.setRoomName(roomName);
                                    }
                                    device.setLinkType(finalLinkType);
                                    FloorBean floor = LLFloorDBManager.getInstance(getContext()).getFloorByFloorSerialNo(floorSerialNo);
                                    if (floor != null) {
                                        device.setFloorName(floor.getFloorName());
                                        device.setFloorSerialNo(floor.getFloorSerialNo());
                                    }
                                    LLDeviceDBManager.getInstance(getContext()).put(device);
                                }
                                toast(R.string.set_success);
                                EventBus.getDefault().post(new RefreshDeviceListEvent());
                            }
                            ((SmartControlActivity) getActivity()).cancel();
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }
                });
    }

    private void setFavourite(boolean isFavourite) {
        Map<String, Object> data = new HashMap<>();
        data.put("isFavourite", isFavourite);
        List<DeviceBean> selectedDevices = mManagerDeviceAdapter.getSelectedData();
        List<String> selectedSerialNos = new ArrayList<>();
        for (DeviceBean deviceBean : selectedDevices) {
            selectedSerialNos.add(deviceBean.getDeviceSerialNo());
        }
        data.put("deviceSerialNoList", selectedSerialNos);
        LLHttpManager.deviceIsFavourite(this, data,
                new HttpCallback<HttpData<Void>>(this) {
                    @Override
                    public void onStart(Call call) {
                        showDialog(null);
                    }

                    @Override
                    public void onSucceed(HttpData<Void> result) {
                        if (result.isRequestSucceed()) {
                            if (selectedSerialNos.size() > 0) {
                                LLDeviceDBManager.getInstance(getContext()).updateDeviceFavourite(isFavourite, selectedSerialNos);
                                toast(R.string.set_success);
                                refreshData();
                                //更新首页是否有常用tab
                                EventBus.getDefault().post(new UpdateFavouriteEvent(isFavourite ? UpdateFavouriteEvent.TYPE_ADD : UpdateFavouriteEvent.TYPE_CANCEL));
                                //刷新首页和当前页面
                                EventBus.getDefault().post(new RefreshDeviceListEvent());
                            }
                            ((SmartControlActivity) getActivity()).cancel();
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }
                });
    }

    private void setShowHomePage(boolean isShow) {
        List<DeviceBean> selectedDevices = mManagerDeviceAdapter.getSelectedData();
        List<String> selectedSerialNos = new ArrayList<>();
        for (DeviceBean deviceBean : selectedDevices) {
            selectedSerialNos.add(deviceBean.getDeviceSerialNo());
        }
        LLHttpManager.deviceIsHomePage(this, selectedSerialNos, isShow,
                new HttpCallback<HttpData<Void>>(this) {
                    @Override
                    public void onSucceed(HttpData<Void> result) {
                        if (result.isRequestSucceed()) {
                            if (selectedDevices != null && selectedDevices.size() > 0) {
                                for (DeviceBean device : selectedDevices) {
                                    device.setIsHomePage(isShow);
                                }
                                LLDeviceDBManager.getInstance(getContext()).putInTx(selectedDevices);
                                toast(R.string.set_success);
                                EventBus.getDefault().post(new RefreshDeviceListEvent());
                            }
                            ((SmartControlActivity) getActivity()).cancel();
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }
                });
    }

    private void deviceIsDisable(boolean isDisable) {
        List<DeviceBean> selectedDevices = mManagerDeviceAdapter.getSelectedData();
        List<String> selectedSerialNos = new ArrayList<>();
        for (DeviceBean deviceBean : selectedDevices) {
            selectedSerialNos.add(deviceBean.getDeviceSerialNo());
        }
        LLHttpManager.deviceIsDisable(this, selectedSerialNos, !isDisable, new HttpCallback<HttpData<Void>>(this) {
            @Override
            public void onSucceed(HttpData<Void> result) {
                if (selectedDevices != null && selectedDevices.size() > 0) {
                    for (DeviceBean device : selectedDevices) {
                        device.setIsDisable(isDisable);
                    }
                    LLDeviceDBManager.getInstance(getContext()).putInTx(selectedDevices);
                    toast(R.string.set_success);
                    refreshData();
                    EventBus.getDefault().post(new RefreshDeviceListEvent());
                }
                ((SmartControlActivity) getActivity()).cancel();
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//        postDelayed(() -> {
//            mAdapter.clearData();
////            mAdapter.setData(analogData());
//            mRefreshLayout.finishRefresh();
//        }, 1000);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//        postDelayed(() -> {
//            mAdapter.addData(analogData());
//            mRefreshLayout.finishLoadMore();
//
//            mAdapter.setLastPage(mAdapter.getCount() >= 100);
//            mRefreshLayout.setNoMoreData(mAdapter.isLastPage());
//        }, 1000);
    }

    @Override
    public StatusLayout getStatusLayout() {
        return mStatusLayout;
    }

    public void setSingleSelect(boolean b) {
        isSingleSelect = b;
    }

    public void setSortData(String deviceSerialNo,int index){

        if (selectType == 4){//kgx
            for(DeviceBean deviceBean : mManagerDeviceAdapter.getData()){
                deviceBean.setTemporary(null);
            }
        }
        for(DeviceBean deviceBean : mManagerDeviceAdapter.getData()){
            if(deviceBean.getDeviceSerialNo().equals(deviceSerialNo)){
                deviceBean.setTemporary(""+index);
                mManagerDeviceAdapter.notifyDataSetChanged();
                break;
            }
        }
    }

    public void setSelectData(Map<String,Integer> selectData){
        this.selectData = selectData;
    }
}